import 'dart:async';

import 'package:flutter/material.dart';
import 'package:moyoung_ble_plugin/moyoung_ble.dart';

import 'modules/notification.dart';

class DevicePage extends StatefulWidget {
  final BleScanBean device;

  const DevicePage({
    Key? key,
    required this.device,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _DevicePage();
  }
}

class _DevicePage extends State<DevicePage> {
  late BleScanBean device = widget.device;

  final _streamSubscriptions = <StreamSubscription<dynamic>>[];
  final MoYoungBle _blePlugin = MoYoungBle();

  int _connetionState = -1;
  bool _autoConnect = false;
  bool _isConn = false;
  bool _reconnect = true;

  String oTAType = "";

  @override
  void initState() {
    super.initState();
    subscriptStream();
  }

  void subscriptStream() {
    _streamSubscriptions.add(
      _blePlugin.connStateEveStm.listen(
        (ConnectStateBean event) {
          setState(() {
              setState(() {
                _connetionState = event.connectState;
                _autoConnect = event.autoConnect;
                if (_connetionState == 2) {
                  _isConn = true;
                } else {
                  _isConn = false;
                }

                if (event.connectState == 2) {
                  addStepsListen();
                } else if (event.connectState == 0) {
                  // delayConnect();
                }
              });
          });
        },
      ),
    );
  }

  void delayConnect() {
    if (_reconnect) {
      Timer(const Duration(seconds: 3), () => _blePlugin.connect(ConnectBean(autoConnect: false, address: device.address)));
    }
  }

  void addStepsListen() {
    _streamSubscriptions.add(
      _blePlugin.stepsChangeEveStm.listen(
        (StepsChangeBean event) {
          setState(() {
            // print("stepEvent: $event");
            // _stepsChange = event.stepsInfo.steps;
          });
        },
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    for (final subscription in _streamSubscriptions) {
      subscription.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Device'),
        ),
        body: Center(
          child: ListView(
            children: <Widget>[
              Text(device.name + ',' + device.address),
              Text('connectionState: $_connetionState'),
              Text('autoConnect: $_autoConnect'),
              Text('isConn= $_isConn'),
              ElevatedButton(
                  child: const Text('isConnected()'),
                  onPressed: () async {
                    bool isConn = await _blePlugin.isConnected(device.address);
                    // bool isConn = await _blePlugin.isConnected("D3:C3:1D:46:73:7A");
                    setState(() {
                      _isConn = isConn;
                    });
                  }),
              ElevatedButton(
                  child: const Text("connect(false)"),
                  onPressed: () {
                    _blePlugin.connect(ConnectBean(autoConnect: false, address: device.address));
                    _reconnect = true;
                    // print(device.address);
                    // _blePlugin.connect("EC:28:65:94:61:1D");
                    // _blePlugin.connect("D3:C3:1D:46:73:7A");
                  }),
              ElevatedButton(
                  child: const Text("connect(true)"),
                  onPressed: () {
                    _blePlugin.connect(ConnectBean(autoConnect: true, address: device.address));
                    _reconnect = true;
                    // print(device.address);
                    // _blePlugin.connect("EC:28:65:94:61:1D");
                    // _blePlugin.connect("D3:C3:1D:46:73:7A");
                  }),
              ElevatedButton(
                  child: const Text('disconnect()'),
                  onPressed: () async {
                    _reconnect = false;
                    bool connetionState = await _blePlugin.disconnect;
                    setState(() {
                      if (connetionState) {
                        _connetionState = 0;
                      }
                    });
                  }),
              // ElevatedButton(
              //     child: const Text('closeGatt()'),
              //     onPressed: () async {
              //       bool connetionState = await _blePlugin.closeGatt;
              //       setState(() {
              //         if (connetionState) {
              //           _connetionState = 0;
              //         }
              //       });
              //     }),
              ElevatedButton(
                  child: const Text('reconnect()'),
                  onPressed: () {
                    _blePlugin.reconnect;
                  }),
              ElevatedButton(
                  child: const Text('connectDevice(false)'),
                  onPressed: () {
                    _blePlugin.connectDevice(ConnectDeviceBean(
                      address: device.address,
                      peripheral: "edsd",
                      autoConnect: false
                    ));
                  }),
              const Text("Module functions are as follows:",
                  style: TextStyle(
                    fontSize: 20,
                    height: 2.0,
                  )),
              ElevatedButton(
                  onPressed: () {
                    if (_isConn) {
                      Navigator.push(context, MaterialPageRoute(builder: (context) {
                        return NotificationPage(
                          blePlugin: _blePlugin,
                        );
                      }));
                    }
                  },
                  child: const Text("17-Notification")),
            ],
          ),
        ),
      ),
    );
  }
}
